var mqtt = require('mqtt');

class TMqClient {
    constructor() {
        this.config = {
            mqClientId: ['mqid', ((new Date()).getTime()).toString(), parseInt(1000 * Math.random()).toString()].join(''),
            mqUrl: "tcp://hhuciot.mqtt.iot.bj.baidubce.com:1883",
            mqUid: "hhuciot/mcu",
            mqPwd: "9vG6KT6V64S2uS3P"
        }
        this.client = null;
        this.events = {
            onConnect: function() {},
            onDisConnect: function() {},
            onMsg: function(msg, topic) {}
        };
        this.actionHandler = {};
    }
    open() {
        var me = this;
        return new Promise((success, faild) => {
            try {
                if (me.config.mqClientId == null || me.config.mqClientId == "") {
                    me.config.mqClientId = ['mqid', ((new Date()).getTime()).toString(), parseInt(1000 * Math.random()).toString()].join('');
                }
                var options = {
                    username: me.config.mqUid,
                    password: me.config.mqPwd,
                    clientId: me.config.mqClientId
                };
                me.client = mqtt.connect(me.config.mqUrl, options);
                me.client.on('connect', function() {
                    console.log("connected to broker. topic:");
                    if (me.events.onConnect || me.events.onConnect != null) {
                        try {
                            me.events.onConnect();
                        } catch (eer) {
                            console.log(eer);
                        }
                    }
                    success();
                    /*
                            "hh/app/"+config.appCode+"/#",
                            "hh/channel/"+config.channelId+"/#",
                            "hh/client/"+config.clientId+"/#"
                    var topics = [
                        "hh/app/" + me.config.appCode + "/#",
                        "hh/channel/" + me.config.channelId + "/#",
                        "hh/client/" + me.config.mqClientId + "/#",
                        "hh/mcu/" + me.config.mcuId + "/#"
                    ];
                    client.subscribe(topics);
                    */
                });
                me.client.on('close', function() {
                    console.log("connection closed");
                    if (me.events.onDisConnect || me.events.onDisConnect != null) {
                        try {
                            me.events.onDisConnect();
                        } catch (eer) {
                            console.log(eer);
                        }
                    }
                });
                me.client.on('message', function(topic, message) {
                    var msg = JSON.parse(message.toString());
                    try {
                        var isActionHandler = false;
                        if (msg.msgId && msg.msgId != null && msg.msgId != "") {
                            var action = me.actionHandler[msg.msgId];
                            if (action && action != null && action instanceof Function) {
                                isActionHandler = true;
                                action(msg, topic);
                            }
                        }

                        if ((!isActionHandler) && me.events.onMsg || me.events.onMsg != null) {
                            try {
                                me.events.onMsg(msg, topic);
                            } catch (eer) {
                                console.log(eer);
                            }
                        }

                    } catch (exr) {
                        console.log(exr)
                    }
                });
            } catch (er) {
                console.log(er);
                success();
            }
        })
    }
    close() {
        var me = this;
        try {
            if (me.client && me.client != null && me.client.isConnected()) {
                me.client.close();
            }
        } catch (er) {
            console.log(er);
        }
    }
    registAction(ac, handler) {
        var me = this;
        try {
            me.actionHandler[ac] = handler;
        } catch (er) {
            console.log(er);
        }
    }
    subscribe(topics) {
        var me = this;
        try {
            if (me.client && me.client != null && me.client.isConnected()) {
                me.client.subscribe(topics);
            }
        } catch (er) {
            console.log(er);
        }
    }
    sendMsg(topic, msg) {
        var me = this;
        try {
            if (me.client && me.client != null) {
                me.client.publish(topic, JSON.stringify(msg));
            }
        } catch (er) {
            console.log(er);
        }
    }
    sendRespMsg(reqId, topic, msg) {
        var me = this;
        try {
            var sendMsg = JSON.parse(JSON.stringify(msg));
            sendMsg.reqId = reqId;
            me.sendMsg(topic, sendMsg)
        } catch (er) {
            console.log(er);
        }
    }
}
module.exports = {
    TMqClient: TMqClient
}